package demo.collidingSpheres;

import static org.lwjgl.opengl.GL11.glColor3f;

import org.lwjgl.util.glu.Sphere;

import engine.collider.ContactPoint;
import engine.collider.bounds.BoundingSphere;
import engine.gameObject.DynamicObject;
import engine.util.vector.Vector;

public class DynamicSphere extends DynamicObject{

	private Sphere sphere;
	private float radius;
	
	private double[] newVelocity;
	
	public DynamicSphere(float radius) {
		this.radius = radius;
		
		//set the radius of the object for frustum culling
		setBounds(0, 0, 0, radius);
		
		//set the bounding element
		BoundingSphere bounds = new BoundingSphere();
		bounds.setRadius(radius);
		addBoundingElement(bounds);
		
		sphere = new Sphere();
		
		setVelocity(Vector.mult(Vector.normalize(Vector.sub(Vector.random(3, 1), new double[]{1, 1, 1})), 5));;
		getVelocity()[0] = 0;
		setPosition(Vector.sub(Vector.random(3, 8), new double[]{4, 4, 4}));
		setPosition(0, getPosY(), getPosZ());
//		setPosition(0, 10, 0);
	}
	
	@Override
	public void render(float timeElapsed) {
		glColor3f(1, 1, 0);
		
		sphere.draw(radius, 10, 10);
	}
	
	@Override
	public void update(float timeElapsed) {
		if(newVelocity != null) {
			setVelocity(newVelocity);
			newVelocity = null;
		}
		
		makeRigidBody(timeElapsed);
	}
	
	private void makeRigidBody(double timeElapsed) {
		gravity(timeElapsed);
		
		friction(timeElapsed);
	}
	
	private void gravity(double timeElapsed) {
		double vy = getVelocity()[1];
		
		getVelocity()[1] -= 0.01 * timeElapsed;
		
		if(vy > 0 && getVelocity()[1] < 0) {
			getVelocity()[1] = 0;
		}
	}
	
	private void friction(double timeElapsed) {
		for(int i = 0; i < getVelocity().length; i++) {
			getVelocity()[i] -= getVelocity()[i] / 1000 * timeElapsed;
		}
	}
	
	@Override
	public void collided(ContactPoint contactPoint, double timeLeft) {
		double[] vShort = Vector.mult(contactPoint.getV(), -Vector.mult(contactPoint.getV(), getVelocity()));
		setVelocity(Vector.add(Vector.mult(vShort, 2), getVelocity()));
		
		makeRigidBody(timeLeft);
		
		if(contactPoint.getDistance() < 0.00001) {
//			System.out.println("reset velocity");
			setVelocity(0, 0, 0);
		}
		
//		System.out.println("speed: " + Vector.length(getVelocity()));
	}
}
